<template>
  <div v-if="show" class="captcha-mask" @click.self="handleClose">
    <div class="captcha-container">
      <button class="refresh-btn" @click="resetCaptcha" aria-label="刷新验证码">
        <i class="icon-refresh"></i>
      </button>

      <div
        class="slider-thumb"
        role="slider"
        :aria-valuenow="thumbPosition"
        :aria-valuemin="0"
        :aria-valuemax="puzzleAreaWidth"
      ></div>
      <div class="puzzle-area">
        <!-- 加载状态 -->
        <div v-if="!bgLoaded" class="image-loading">
          <div class="loader"></div>
        </div>

        <!-- 拼图背景 -->
        <div v-show="bgLoaded" class="puzzle-bg" :style="bgStyle"></div>

        <!-- 拼图块 -->
        <div
          class="puzzle-piece"
          :style="pieceStyle"
          @mousedown="startDrag"
          @touchstart="startDrag"
        ></div>

        <!-- 目标缺口 -->
        <div class="target-gap" :style="gapStyle" :class="{ success: isVerified }"></div>
      </div>

      <!-- 控制区域 -->
      <div class="control-area">
        <div class="slider-track">
          <div
            class="slider-thumb"
            :style="{
              left: thumbPosition + 'px',
              backgroundColor: sessionExpired ? '#409eff' : 'initial',
            }"
            @mousedown="startDrag"
            @touchstart="startDrag"
          ></div>
        </div>
        <div class="tip-text">{{ errorMessage }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'

const props = defineProps({
  show: Boolean,
})

watch(
  () => props.show,
  (newVal) => {
    if (newVal) {
      resetCaptcha()
    }
  },
)

const emit = defineEmits(['success', 'close'])

// 验证码参数
const bgImage = ref('')
const pieceSize = 50 // 拼图块尺寸
const gapPosition = ref(0) // 缺口位置
const thumbPosition = ref(0) // 滑块位置
const isDragging = ref(false)
const bgLoaded = ref(false)
const isVerified = ref(false)
const errorMessage = ref('')
const sessionExpired = ref(false) // 用来标记登录是否超时

// 初始化
onMounted(() => {
  // 随机生成缺口位置（示例）
  gapPosition.value = Math.random() * (300 - pieceSize)
  // 加载背景图片
  loadImage('images/pt.png')
})

// 样式计算
const bgStyle = computed(() => ({
  backgroundImage: `url(${bgImage.value})`,
  backgroundSize: 'cover',
}))

const pieceStyle = computed(() => ({
  left: `${thumbPosition.value}px`,
  backgroundPosition: `-${thumbPosition.value}px 0`,
}))

const gapStyle = computed(() => ({
  left: `${gapPosition.value}px`,
}))

// 交互逻辑
const startDrag = (e) => {
  isDragging.value = true
  const startX = e.clientX
  const startLeft = thumbPosition.value

  const moveHandler = (e) => {
    if (!isDragging.value) return
    const deltaX = e.clientX - startX
    thumbPosition.value = Math.max(
      0,
      Math.min(startLeft + deltaX, puzzleAreaWidth.value - pieceSize),
    )
  }

  const upHandler = () => {
    isDragging.value = false
    validate()
    document.removeEventListener('mousemove', moveHandler)
    document.removeEventListener('mouseup', upHandler)
  }

  document.addEventListener('mousemove', moveHandler)
  document.addEventListener('mouseup', upHandler)
}

// 验证逻辑
const tolerance = 5 // 允许误差
const checkSessionExpired = () => {
  // 示例检测逻辑
  const lastActivity = localStorage.getItem('lastActivity')
  const expired = Date.now() - lastActivity > 30 * 60 * 1000
  sessionExpired.value = expired

  if (expired) {
    errorMessage.value = '会话已过期，请重新登录'
  }
}
// 重置逻辑
const resetCaptcha = () => {
  checkSessionExpired()
  errorMessage.value = '请拖动滑块完成验证' // 初始化提示
  thumbPosition.value = 0
  gapPosition.value = Math.random() * (300 - pieceSize)
  isVerified.value = false
  errorMessage.value = ''
  bgLoaded.value = false
  sessionExpired.value = false // 重置登录超时状态
}
const loadImage = (url) => {
  bgLoaded.value = false
  const img = new Image()
  img.src = url
  img.onload = () => {
    bgImage.value = url
    bgLoaded.value = true
  }
  img.onerror = () => {
    // 处理错误
  }
}
const validate = () => {
  if (Math.abs(thumbPosition.value - gapPosition.value) < tolerance) {
    isVerified.value = true
    errorMessage.value = '验证成功！'
    // 延迟关闭
    setTimeout(() => {
      emit('success')
      emit('close')
    }, 1000)
  } else {
    errorMessage.value = '验证失败，请重试'
    resetCaptcha()
  }
}
// 判断是否登录超时并更新状态
// const checkSessionExpired = () => {
//   // 这里可以加入你的判断逻辑来检测登录是否超时
//   // 比如检查Token是否过期等
//   if (sessionExpired.value) {
//     sessionExpired.value = true
//   }
// }

// 暴露复位方法给父组件
defineExpose({ resetCaptcha })
// 新增响应式变量
const puzzleAreaWidth = ref(360) // 默认值，需与实际宽度匹配

// // 在 mounted 中获取实际宽度
// onMounted(() => {
//   const areaElem = document.querySelector('.puzzle-area')
//   puzzleAreaWidth.value = areaElem ? areaElem.offsetWidth : 360
//   gapPosition.value = Math.random() * (puzzleAreaWidth.value - pieceSize)
// })

// // 修改滑块限制逻辑
// thumbPosition.value = Math.max(
//   0,
//   Math.min(startLeft + deltaX, puzzleAreaWidth.value - pieceSize)
// )
</script>

<style scoped>
.captcha-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.captcha-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  width: 360px;
}

.puzzle-area {
  position: relative;
  height: 200px;
  border: 1px solid #ddd;
  overflow: hidden;
}

.puzzle-bg {
  width: 100%;
  height: 100%;
  filter: brightness(0.8);
}

.puzzle-piece {
  position: absolute;
  width: 50px;
  height: 50px;
  background: url('/images/pt.png');
  cursor: grab;
  transition: left 0.1s;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
  will-change: transform;
  transform: translateZ(0);
}

.target-gap {
  position: absolute;
  width: 50px;
  height: 50px;
  border: 2px dashed #409eff;
  background: rgba(64, 158, 255, 0.1);
}

.control-area {
  margin-top: 20px;
}

.slider-track {
  position: relative;
  height: 40px;
  background: #f5f5f5;
  border-radius: 20px;
}

.slider-thumb {
  position: absolute;
  width: 40px;
  height: 40px;
  background: #409eff;
  border-radius: 50%;
  cursor: grab;
  top: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  transition: left 0.1s cubic-bezier(0.4, 0, 0.2, 1);
}

.tip-text {
  text-align: center;
  color: #666;
  margin-top: 10px;
}
</style>
